'use strict';

var model = require('../model/vendor.js');
var debug = require('debug')('vendor');

function* save(json) {
	var item = new model({
		email: json.email,
		name: json.name,
		password: json.password
	});

	var errCode = 0;
	var errMsg = null;
	try {
		var result = yield item.save();
		if (result.errors) {
			errCode = 1;
			errMsg = result.toString();
		} else {
			errMsg = result._doc;
		}
	} catch (e) {
		errCode = 1;
		errMsg = e.toString();
	}

	return {
		errCode: errCode,
		errMsg: errMsg
	}

}

function* findById(id) {
	debug('findById, id=' + id);
	try {
		var result = yield model.findOne({
			_id: id
		});
		return result._doc;
	} catch (e) {
		return e.toString();
	}
}

function* check(json) {
	try {
		var result = yield model.findOne({
			email: json.email,
			password: json.password
		}, {
			password: 0
		});
		if (!result.errors && result._doc) {
			return result._doc;
		}
	} catch (e) {}
	return false;
}


module.exports = {
	save: save,
	findById: findById,
	check: check
};